///////////////////////////////////////////////////////////////////////////////
// Project: Hoyo Client Game
//
// hy_db_logic.h
// Created: 2013-7-16
// Author: Like Cheng
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "hy_includes.h"

#include "hy_db_const.h"

#include <client/dbclient.h>

using namespace mongo;

#ifndef __HY_DB_LOGIC_H__
#define __HY_DB_LOGIC_H__

class hy_db
{
public:
	hy_db();
	virtual ~hy_db();
	void				init();

public:
	bool			connect_db(const char* ip_str, const char* db_name = NULL, const char* name = NULL, const char* pwd = NULL );

	bool			run_command(const std::string& db_name_str, mongo::BSONObjBuilder& c, mongo::BSONObj& b);
	std::string		convert_server_db_name(const std::string& db_str);
	void			ensure_index(const std::string &collection, const std::string &key);
	void			ensure_index(const std::string &collection, Json::Value &keyJson);

	bool			insert_bson( const char* db, mongo::BSONObjBuilder& query);
	bool			insert_bson( const char* db, mongo::BSONObj& query);
	bool			insert_json( const char* db, Json::Value &v );

	bool			bson_exist(const std::string& db_name_str, mongo::BSONObjBuilder& query);
	bool			update_bson( const char*, mongo::BSONObjBuilder& key, mongo::BSONObjBuilder& value, bool is_insert = true );
	bool			update_bson( const char*, mongo::BSONObjBuilder& key, mongo::BSONObj& value, bool is_insert = true );
	bool			update_bson( const char*, Json::Value& key, mongo::BSONObj& value, bool is_insert = true );

	bool			remove( const std::string& db_name_str, mongo::BSONObjBuilder& query, bool justone = true );
	bool            load_collection_data( mongo::BSONObjBuilder& query, const char* collection, Json::Value& json );

	int				load_collection(const std::string &collection, const Json::Value &key, Json::Value &value);
	int				save_collection(const std::string &collection, const Json::Value &key, const Json::Value &value);
	int				remove_collection(const std::string &collection, const Json::Value &key);

	int				get_autoinc_id(const std::string& db_name, const std::string& table);

	void			drop_collection(const std::string& collection);

	Json::Value		find_json_val( const char* db_name_str, mongo::BSONObjBuilder& query);
	mongo::BSONObj	find_bson_val( const char* db_name_str, mongo::BSONObjBuilder& query);

	mongo::BSONObj	find_json(const char* db_name_str, const char* key_word );

	mongo::DBClientConnection*			get_db_conn(){ return &m_db_conn; }
private:

	mongo::DBClientConnection			m_db_conn;
};
typedef std::map< std::string, hy_db* > hy_db_map;

class hy_db_logic
{
public:
	hy_db_logic();
	virtual ~hy_db_logic();

	void				init();

	static hy_db_logic*	get_instance();
	static hy_db*		instance( const char* db = DS );
private:
	hy_db_map		m_db_map;
};


#endif